from wheels.pi.aio.Reactor import EventHandler


class AsyncProcessor(object):

    class _ReactiveHandler(EventHandler):

        def __init__(self, processor, op, proactor, handler):
            EventHandler.__init__(self, op.handle())
            self._processor = processor
            self._op = op
            self._proactor = proactor
            self._handler = handler

        def handle_event(self, type_):
            self._processor._reactor.unregister(type_, self)
            self._processor._handle_event(self._op, self._proactor, self._handler)


    def __init__(self, reactor):
        self._reactor = reactor


    def register(self, op, proactor, handler):
        reactive = AsyncProcessor._ReactiveHandler(self, op, proactor, handler)
        if op.type_() in ("accept", "recv"):
            self._reactor.register("r", reactive)
        elif op.type_() in ("connect", "send"):
            self._reactor.register("w", reactive)
        else:
            raise ValueError, "unknown operation type"


    def _handle_event(self, op, proactor, handler):
        proactor.dispatch(op.type_(), handler, op.exec_())
